<?php
	/**
	* @File name:	_class.mysql.inc.php
	* @Desription:	mysql
	* @Author:	 	jinxin<jx@178.com>   
	* @Date:	 	Fri Jun 03 17:19:58 CST 2011
	* @Copyright 	Copytright (c) 2008-2011 178.COM Co., Ltd.
	* @version	 	$Id $
	*/
	
	class MysqlDB {
		
		/**
		 * mysql链接
		 * @var resouce
		 */
		
		public $con;
		
		/**
		 * 当前库
		 * @var string
		 */
		public $cur;
		
		/**
		 * 用户名
		 * @var string
		 */
		
		private $username;
		
		/**
		 * 密码
		 * @var string
		 */
		
		private $password;
		
		/**
		 * 数据库名
		 * @var string
		 */
		
		private $dbName;
		
		/**
		 * 字符集设置
		 * @var string
		 */
		
		private $charset;
		
		/**
		 * 调试开关
		 * @var bool
		 */
		
		public $debug;
		
		/**
		 * 上一次插入id
		 * @var int
		 */
		
		public $insertid;
		
		/**
		 * 构造函数
		 * @param string $host
		 * @param string $port
		 * @param string $username
		 * @param string $password
		 * @param string $dbName
		 * @param string $charset
		 * @param bool $debug
		 */
		public function __construct($host, $port, $username, $password, $dbName, $charset, $debug=false)
		{
			$this->host = $host;
			$this->port = $port;
			$this->username = $username;
			$this->password = $password;
			$this->dbName = $dbName;
			$this->charset = $charset;
			$this->debug = $debug;
			$this->connect();
		}
		
		/*
		 * 析构函数
		 */
		public function __destruct()
		{
			if($this->con)
			mysql_close($this->con);
		}
		
		/**
		 * 连接数据库
		 *
		 * @return 连接资源
		 */
		public function connect()
		{
			$this->con = mysql_connect(
				$this->host.':'.$this->port,
				$this->username,
				$this->password,
				true
			);
			if(!$this->con){
				exit($_SERVER['config']['lang']['sys']['no_db']);
			}
			$this->query("USE {$this->dbName}");
			$this->query("SET NAMES {$this->charset}");
			return $this->con;
		}
		
		/**
		 * 执行sql语句，返回资源
		 *
		 * @param string $sql
		 * @return rresource
		 */
		public function query($sql)
		{
			$this->writeLog($sql);
			return mysql_query($sql,$this->con);
		}
		
		/**
		 * 查询符合条件的全部内容
		 *
		 * @param sql语句 $sql
		 * @param string 如果是某个特定的字段，加上字段名返回单列的数据 $fieldName
		 * @return array
		 */
		public function fetchAll($sql,$fieldName = '')
		{
			$res = $this->query($sql);
			$rows = array();
			while ($row = mysql_fetch_assoc($res)){
				if ($fieldName != '' && isset($row[$fieldName])){
					$rows[] = $row[$fieldName];
				}else {
					$rows[] = $row;
				}
			}
			$this->free($res);
			return $rows;
		}
		
		/**
		 * 查询单行数据
		 *
		 * @param string $sql
		 * @return array
		 */
		public function fetchRow($sql)
		{
			$res = $this->query($sql." LIMIT 1");
			$row = mysql_fetch_assoc($res);
			$this->free($res);
			return $row;
		}
		
		/**
		 * 查询某一个字段的值
		 *
		 * @param string sql语句 $sql
		 * @param string $field
		 * @return string
		 */
		public function fetchField($sql,$field)
		{
			$res = mysql_query($sql,$this->con);
			$this->writeLog($sql);
			$row = mysql_fetch_assoc($res);
			$this->free($res);
			return $row[$field];
		}
		
		/**
		 * insert row 插入一行
		 *
		 * @param string 表名 $table
		 * @param array 要插入的数据数组，键是字段名，底层转义已做 $data
		 * @return int 插入之后的新id
		 */
		public function insertRow($table,$data)
		{
			$field = array_keys($data);
			$fields = implode('`,`',$field);
			$values = $this->formatData($data);
			$sql = "INSERT INTO {$table} (`{$fields}`) VALUES {$values}";
			$this->query($sql);
			return $this->insertid = $this->fetchField("SELECT LAST_INSERT_ID( ) AS id",'id');
		}
		
		/**
		 * insert row 插入多行
		 *
		 * @param string 表名 $table
		 * @param array 要插入的数据数组，键是字段名，底层转义已做 $data
		 * @return int 插入之后的新id
		 */
		public function insertRows($table,$data)
		{
			$rows = count($data);
			if ($rows < 1){
				return;
			}else{
				$field = array_keys($data[0]);
				$fields = implode('`,`',$field);
				$sql = "INSERT INTO {$table} (`{$fields}`) VALUES ";
				if ($rows < 1000){
					foreach ($data as $k=>$row){
						$sql_arr[$k] = $this->formatData($row);
					}
					$sql .= implode(',',$sql_arr);
					$res = $this->query($sql);
				}else {
					$data_row = array();
					for ($i=1;$i<=$rows;$i++){
						$k = $i-1;
						$data_row[] = $data[$k];
						if ($i % 1000 == 0 || $i=$rows){
							$sql_arr = array();
							foreach ($data_row as $key=>$val){
								$sql_arr[$key] = $this->formatData($val);
							}
							$sqls = $sql.implode(',',$sql_arr);
							$res = $this->query($sqls);
							$data_row = array();
							unset($sql_arr);
							unset($sqls);
							usleep(100);
						}
					}
				}
			}
		}
		
		/**
		 * 格式化数组的值，转义掉“\”，“'”，“"”，并按照顺序排成插入的value格式
		 *
		 * @param array $data
		 * @return string
		 */
		public function formatData($data)
		{
			foreach ($data as $k => $v){
				$val[$k] = is_numeric($v) ? $v : "'".mysql_escape_string($v)."'";
			}
			$values = '('.implode(',',$val).')';
			return $values;
		}
		
		private function writeLog($sql){
			if (defined('LOG_PATH') && $this->debug == 1) {
				$filepath = LOG_PATH.$_SERVER['HTTP_HOST'].'_sql.log';
				$log  = '['.date('Y-m-d H:i:s').']	'.$sql."\n";
				file_put_contents($filepath,$log,FILE_APPEND);
			}
		}
		
		/**
		 * 释放资源
		 *
		 * @param resources $res
		 */
		public function free($res)
		{
			mysql_free_result($res);
		}
		
	}